package nettypro.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName BIOServer
 * @Description TODO
 * @Author zeny
 * @Date 2020/3/21 0021 0:30
 */
@SuppressWarnings("all")
public class BIOServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器启动了......");
        while (true) {
            final Socket accept = serverSocket.accept();
            System.out.println("连接到一个客户端");
            executorService.execute(() -> {
                //和客户端通讯
                headler(accept);
            });
            Thread.sleep(1_1000);
        }
    }

    public static void headler(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
            InputStream in = socket.getInputStream();
            while (true) {
                int read = in.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                }else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
